//
//  JYTMyInformationViewController.m
//  JYT_IOS
//
//  Created by nxa-chengjinhui on 2017/1/4.
//  Copyright © 2017年 nxa-yuanguoxiang. All rights reserved.
//

#import "JYTMyInformationViewController.h"
#import "User.h"
#import "JYTMyInformationTableViewCell.h"
#import "JYTNameUpdateViewController.h"
#import "JYTTelephoneViewController.h"
#import "UIImageView+WebCache.h"
@interface JYTMyInformationViewController ()<UITableViewDelegate,UITableViewDataSource,JYTMyInformationTableViewCellDelegate,UIActionSheetDelegate,UIAlertViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
{
    UIImagePickerController *picker;
}
@property (nonatomic,strong) UITableView *tabview;//

@property (nonatomic,strong) NSMutableArray *dataSource;//标题

@property (nonatomic,strong) NSMutableArray *detailSource;//详情

@property (nonatomic,strong) UITextField *textField;

@property (nonatomic,strong) UIImageView *imgview;

@end

@implementation JYTMyInformationViewController

//-(NSMutableArray *)dataSource{
//    if (!_dataSource) {
//        _dataSource = [NSMutableArray array];
//    }
//    return _dataSource;
//}
//
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    NSDictionary *dic = @{@"lftBtnBgImg":@"ic_goback",
                          @"lftBtnTitle":@"no",
                          @"pageTitle":@"个人信息",
                          @"rhtBtnBgImg":@"no",
                          @"rhtBtnTitle":@"no"};
    
    [self setNavgationBarWithDic:dic];
    
    //数据源
//    [self data];
    
    [self initTableview];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self data];
    [self.tabview reloadData];
}

-(void)data{
    
    NSArray *arr1 = [NSArray arrayWithObjects:@"头像",@"昵称", nil];
    NSArray *arr2 = [NSArray arrayWithObjects:@"真名",@"性别",@"手机号码", nil];
    NSArray *arr3 = [NSArray arrayWithObjects:@"关注城市",@"驾照类型",@"付费模式", nil];
    
    self.dataSource  = [NSMutableArray arrayWithObjects:arr1,arr2,arr3, nil];
    
    User *user =[[JYTUserManager shared] getUser];
    //昵称
    NSString *smallName = @"";
    if ([[[JYTUserManager shared] getNikeName] isKindOfClass:[NSNull class]] || [[JYTUserManager shared] getNikeName].length==0) {
        smallName = @"还未设置";
    }else{
        smallName = [[JYTUserManager shared] getNikeName];
    }
    //性别
    NSString *sex = @"";
    if ([user.gender isKindOfClass:[NSNull class]]) {
        sex = @"未知";
    }else{
        sex = user.gender;
    }
    //驾照类型
    NSString *carKind = @"";
    if ([user.gender isKindOfClass:[NSNull class]]) {
        carKind = @"暂无";
    }else{
        carKind = user.learnType;
    }
    
    NSArray *array1 = [NSArray arrayWithObjects:@"",smallName, nil];
    NSArray *array2 = [NSArray arrayWithObjects:@"张三",sex,user.phone, nil];
    NSArray *array3 = [NSArray arrayWithObjects:user.cityName,carKind,@"先学后付", nil];
    
    self.detailSource = [NSMutableArray arrayWithObjects:array1,array2,array3, nil];
}
//布局
-(void)initTableview{
    
    self.tabview = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, CURRENT_SCREEN_WIDTH, CURRENT_SCREEN_HEIGHT-64) style:UITableViewStyleGrouped];
    self.tabview.delegate = self;
    self.tabview.dataSource = self;
    self.tabview.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tabview.scrollEnabled = NO;
    [self.tabview registerClass:[JYTMyInformationTableViewCell class] forCellReuseIdentifier:@"inforCell"];
    [self.view addSubview:self.tabview];
}
#pragma mark----UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 2;
    }else {
        return 3;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JYTMyInformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"inforCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    [cell setTitile:self.dataSource[indexPath.section][indexPath.row] detail:self.detailSource[indexPath.section][indexPath.row]];
    if (indexPath.section==0 && indexPath.row==0) {
        cell.imageview.hidden = NO;
        cell.imageview.layer.masksToBounds = YES;
        cell.imageview.layer.cornerRadius = 25;
        [cell.imageview sd_setImageWithURL:[NSURL URLWithString:[[JYTUserManager shared] getUserHeadUrl]] placeholderImage:[UIImage imageNamed:@"tx_w"]];
//        cell.imageview.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[JYTUserManager shared] getUser].headUrl]]];
//        [cell.TitBtn setBackgroundImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[JYTUserManager shared] getUser].headUrl]]] forState:UIControlStateNormal];
    }
    if (indexPath.section==0 || (indexPath.section==1 && indexPath.row!=0)) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.TitBtn.tag = indexPath.section + indexPath.row + 100;
        cell.delegate = self;
    }
    return cell;
}
#pragma mark----UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0 && indexPath.row==0) {
        return 60;
    }else{
        return 44;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 10;
    }else{
        return 20;
    }
}
#pragma  mark ---JYTMyInformationTableViewCellDelegate
-(void)chooseBtnClicked:(UIButton *)bttn{
    switch (bttn.tag) {
        case 100://更换头像
//            NSLog(@"1");
        {
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"请选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
            sheet.tag = 880;
            [sheet showInView:self.view];
        }
            break;
        case 101://更改昵称
//            NSLog(@"2");
//            [self.navigationController pushViewController:[[JYTNameUpdateViewController alloc] init] animated:YES];
            [self pushViewController:[[JYTNameUpdateViewController alloc] init]];
            break;
        case 102://更改性别
//            NSLog(@"3");
        {
            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"请选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男",@"女", nil];
            [sheet showInView:self.view];
        }
            break;
        case 103://更换手机号码
//            NSLog(@"4");
        {
            [self alert:@"密码验证"];
        }
            
            break;
        default:
            break;
    }
}
#pragma mark ---UIActionSheetDelegate
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag==880) {//照片选择
        if (buttonIndex==0) {
            MyLog(@"拍照");
            [self getCamera:UIImagePickerControllerSourceTypeCamera];
        }else if (buttonIndex==1){
            MyLog(@"相册");
            [self getCamera:UIImagePickerControllerSourceTypePhotoLibrary];
        }
    }else{//性别选择
        if (buttonIndex==0) {
            MyLog(@"男");
            [self alertSex:@"1"];
        }else if (buttonIndex==1){
            MyLog(@"女");
            [self alertSex:@"0"];
        }
    }
}

#pragma mark---UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        
        if (self.textField.text.length==0) {
//            [JYTPublicClass showMessage:@"请输入密码！"];
            [self alert:@"请输入密码！"];
        }else{
            //判断密码是否输入正确
            
            NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];
            
            //请求验证
            JYTHttpClient *httpManager = [JYTHttpClient sharedInstance];
            httpManager.urlType = userCenterUrl;
            NSString *md5pass = [httpManager md5_base64:self.textField.text];
            
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setObject:username forKey:@"userName"];
            [dic setObject:md5pass forKey:@"Md5Pwd"];
            [dic setObject:@"verifyPwd" forKey:@"CommandCode"];

            
            [httpManager post:@"GetDataInfo" withParam:dic];
            
            httpManager.finishCallbackHandler = ^(id result, NSString *code, NSString *msg){
                
//                NSDictionary *dic = result;
                //            dic = dic[@"data"];
                
                MyLog(@"验证成功=====\n\n%@", code);
//                if ([[dic objectForKey:@"ErrorCode"] floatValue] == 0) {
                    [self pushViewController:[[JYTTelephoneViewController alloc] init]];
//                }
            };
            
            httpManager.errorCallbackHandler = ^(NSString * code, NSString * msg) {
                
                MyLog(@"0000000%@", code);
//                [JYTPublicClass showMessage:@"密码输入错误，请重新输入！"];
                if ([code isEqualToString:@"1"]) {
                    [self alert:@"密码输入错误，请重新输入！"];
                }else if ([code isEqualToString:@"-1"]){
                    [JYTPublicClass showMessage:@"服务器异常，请稍后再试！"];
                }
            };
        }
    }
}
-(void)alert:(NSString *)title{
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:title message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
    self.textField = [alertView textFieldAtIndex:0];
    self.textField.placeholder = @"填写用户密码";
    self.textField.secureTextEntry = YES;
    [alertView show];
}
//调用相机
-(void)getCamera:(UIImagePickerControllerSourceType)strr{
    
    picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    picker.allowsEditing = YES;
    picker.sourceType = strr;
//    picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
    
    [self presentViewController:picker animated:YES completion:^{
        self.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    }];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
//        self.imgview.image = info[UIImagePickerControllerEditedImage];
        //压缩图片
        NSData *fileData = UIImageJPEGRepresentation(info[UIImagePickerControllerEditedImage], 1.0);
        //保存图片至相册
//        UIImageWriteToSavedPhotosAlbum(self.imgview.image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
        //上传图片
//        [self uploadImageWithData:fileData];
        MyLog(@"1111选取照片成功");
    
        UIImage *image = [[UIImage alloc] initWithData:fileData];
        NSString *aString = [self UIImageToBase64Str:image];
        [self alertImage:aString];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark 图片保存完毕的回调
- (void) image: (UIImage *) image didFinishSavingWithError:(NSError *) error contextInfo: (void *)contextInf{
    
}
//修改个人信息头像
-(void)alertImage:(NSString *)picture{
    
    JYTHttpClient *manager = [JYTHttpClient sharedInstance];
    manager.urlType = userCenterUrl;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:[[JYTUserManager shared] getUserLoginName] forKey:@"UserName"];
    [dic setObject:[[JYTUserManager shared] getNikeName] forKey:@"NickName"];
    [dic setObject:@"jpg" forKey:@"ImageType"];
    [dic setObject:picture forKey:@"HeadBase64"];
    [dic setObject:@"ModifyUserHead" forKey:@"CommandCode"];
    
    [manager post:@"UpdateDataInfo" withParam:dic];
    
    manager.finishCallbackHandler = ^(id result, NSString *code, NSString *msg) {
        
        NSString *url= result[@"data"];
        
//        [[JYTUserManager shared] setUserHeadUrl:url];
        
        [self viewWillAppear:YES];
        
        MyLog(@"修改头像成功========%@",result);
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"headurl" object:url];
    };
    
    manager.errorCallbackHandler = ^(NSString * code, NSString * msg) {
    
        MyLog(@"修改头像失败++++++++++%@",code);
    };
}

//修改性别
-(void)alertSex:(NSString *)sex{
    
    JYTHttpClient *manager = [JYTHttpClient sharedInstance];
    manager.urlType = userCenterUrl;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:[[JYTUserManager shared] getUserLoginName] forKey:@"UserName"];
    [dic setObject:sex forKey:@"Sex"];
    [dic setObject:@"ModifySex" forKey:@"CommandCode"];
    
    [manager post:@"UpdateDataInfo" withParam:dic];
    
    manager.finishCallbackHandler = ^(id result, NSString *code, NSString *msg) {
        
        
//        [self viewWillAppear:YES];
        
        MyLog(@"修改sex========%@",result);
        
    };
    
    manager.errorCallbackHandler = ^(NSString * code, NSString * msg) {
        
        MyLog(@"修改sex失败++++++++++%@",code);
    };
}

-(NSString *)UIImageToBase64Str:(UIImage *) image
{
    NSData *data = UIImageJPEGRepresentation(image, 1.0f);
    NSString *encodedImageStr = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    return encodedImageStr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
